<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/20
 * Time: 16:39
 */
namespace app\cron\service;

use app\model\Article;
use app\model\Category;
use think\Image;

class ArticleService {
    private static $category;
    private static $article;

    public function __construct() {
        self::$category = new Category();
        self::$article = new Article();
    }

    /**
     * 获取文章列表
     */
    public static function matchArticle() {
        new self;
        $categoryList = self::_getCategoryList();
        if (!empty($categoryList)) {
            foreach ($categoryList as $item) {
                $url = $item['csdn_url'];
                $html = curlCall($url, '', 'GET');
                $rule = '/<div class="article-item-box csdn-tracking-statistics" data-articleid=".*?">(.*?)<\/div>/ies';
                $res = preg_match_all($rule, $html, $match);
                $data = self::_dealArticleList($res, $match[1], $item['id']);
                if (!empty($data)) {
                    self::_insertIntoArticle($data);
                }
            }
        }
        echo "ok";
    }

    public static function matchAeticleDetail() {
        new self;
        $articleList = self::_getArticleList();
        if (!empty($articleList)) {
            foreach ($articleList as $item) {
                $url = $item['csdn_article_url'];
                $html = curlCall($url, '', 'GET');
                $rule = '/<article>(.*?)<\/article>/ies';
                $res = preg_match_all($rule, $html, $match);
                if ($res) {
                    $content = self::_changeImageUrl($item, trim($match[1][0]));
                    $article = [
                        'id' => $item['id'],
                        'content' => $content,
                    ];
                    self::_updateArticle($article);
                }
            }
        }
        echo "ok";
    }

    private static function _changeImageUrl($data, $content) {
        $rule = '/<img src="(.*?)" .*?>/ies';
        $res = preg_match_all($rule, $content, $match);
        $img_urls = [];
        if ($res) {
            $refer = $data['csdn_article_url'];
            foreach ($match[1] as $key => $item) {
                $img = curlCall($item, '', 'GET', $refer);
                $img_url = ROOT_PATH . 'public/static/img/' . $data['id'] . '_' . $key . '.jpg';
                file_put_contents($img_url, $img);
                array_push($img_urls, '/static/img/' . $data['id'] . '_' . $key . '.jpg');
            }
            $temp_content_array = explode('<img src="', $content);
            $total_content = [];
            foreach ($temp_content_array as $key => $item) {
                if ($key != 0) {
                    $temp_src = explode('"', $item);
                    $temp_src[0] = $img_urls[$key-1];
                    $real_src = implode('"', $temp_src);
                    array_push($total_content, $real_src);
                } else {
                    array_push($total_content, $item);
                }
            }
            $content = implode('<img src="', $total_content);
        }
        return $content;
    }

    private static function _getArticleList() {
        $articleList = self::$article->getList([]);
        return $articleList;
    }

    private static function _updateArticle($article) {
        $where = ['id' => $article['id']];
        $insert_data['update_time'] = date('Y-m-d H:i:s');
        $insert_data['content'] = $article['content'];
        self::$article->updateData($where, $insert_data);
    }

    /**
     * @param $count
     * @param $data
     * @param $category_id
     * @return array
     * 处理数据
     */
    private static function _dealArticleList($count, $data, $category_id) {
        $article_array = [];
        if (!empty($count)) {
            foreach ($data as $item) {
                $rule = '/<a href="(.*?)" target="_blank">(.*?)<\/a>/ies';
                $res = preg_match_all($rule, $item, $match);
                $csdn_url = $match[1][0];
                $csdn_url_arr = explode('/', $csdn_url);
                $title = explode('>', $match[2][0]);
                $article = [
                    'csdn_article_url' => $csdn_url,
                    'title' => trim(end($title)),
                    'introduce' => trim($match[2][1]),
                    'category_id' => $category_id,
                ];
                $article_array[end($csdn_url_arr)] = $article;
            }
        }
        return $article_array;
    }

    /**
     * @return array
     * 获取所有类型列表
     */
    private static function _getCategoryList() {
        $categoryList = self::$category->getList();
        return $categoryList;
    }

    private static function _insertIntoArticle($data) {
        foreach ($data as $key => $item) {
            $search_data = [
                'csdn_article_id' => $key,
            ];
            $info = self::$article->getOneInfo($search_data, 'id');
            $insert_data = [
                'title' => $item['title'],
                'csdn_article_id' => $key,
                'csdn_article_url' => $item['csdn_article_url'],
                'introduce' => $item['introduce'],
                'category_id' => $item['category_id'],
            ];
            if (empty($info)) {
                $insert_data['create_time'] = date('Y-m-d H:i:s');
                self::$article->insertData($insert_data);
            } else {
                $where = ['id' => $info['id']];
                $insert_data['update_time'] = date('Y-m-d H:i:s');
                self::$article->updateData($where, $insert_data);
            }
        }
        return true;
    }

}